﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Wms.Core.Entities;
using Wms.Data;

namespace Wms.Web.Controllers
{
	[ApiController]
	[Route("api/[controller]")]
	public class ScanController : ControllerBase
	{
		private readonly WarehouseDbContext _db;

		public ScanController(WarehouseDbContext db)
		{
			_db = db;
		}

		/// <summary>
		/// 扫码入库（PDA 或 RFID 调用）
		/// </summary>
		[HttpPost("stockin")]
		public async Task<IActionResult> StockIn([FromBody] ScanRequest request)
		{
			if (string.IsNullOrEmpty(request.Barcode))
				return BadRequest("条码不能为空");

			// TODO: 这里可以根据条码规则解析物料/批次/库位
			var item = await _db.Items.FirstOrDefaultAsync(x => x.Code == request.Barcode);
			if (item == null)
				return NotFound($"物料未找到，条码={request.Barcode}");

			// 增加库存记录（示例）
			var detail = new StockInDetail
			{
				ItemId = item.Id,
				Quantity = request.Quantity,
				CreateTime = DateTime.Now
			};
			_db.StockInDetails.Add(detail);
			await _db.SaveChangesAsync();

			return Ok(new { message = "入库成功", request.Barcode });
		}

		/// <summary>
		/// 扫码出库
		/// </summary>
		[HttpPost("stockout")]
		public async Task<IActionResult> StockOut([FromBody] ScanRequest request)
		{
			if (string.IsNullOrEmpty(request.Barcode))
				return BadRequest("条码不能为空");

			var item = await _db.Items.FirstOrDefaultAsync(x => x.Code == request.Barcode);
			if (item == null)
				return NotFound($"物料未找到，条码={request.Barcode}");

			// TODO: 校验库存是否足够
			// 这里简单示例：直接记录出库明细
			var detail = new StockOutDetail
			{
				ItemId = item.Id,
				Quantity = request.Quantity,
				CreateTime = DateTime.Now
			};
			_db.StockOutDetails.Add(detail);
			await _db.SaveChangesAsync();

			return Ok(new { message = "出库成功", request.Barcode });
		}
	}

	/// <summary>
	/// 扫码请求 DTO
	/// </summary>
	public class ScanRequest
	{
		public string Barcode { get; set; }
		public int Quantity { get; set; } = 1;
		public string Operator { get; set; }  // 操作员
	}
}
